import React from 'react';
import { Button, Form, Input } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { v4 as uuidv4 } from 'uuid';

interface MultipleChoiceInputProps {
  onChange: (e: any) => void;
  mode?: 'one' | 'multiple';
  maxLen?: number;
}

interface modalProps extends React.FC<MultipleChoiceInputProps> {
}

export const MultipleChoiceInput: modalProps = ({
                                                  onChange,
                                                  mode = 'multiple',
                                                  maxLen = 15
                                                }) => {
  const [result, setResult] = React.useState<Array<any>>([{ name: '', value: '', id: uuidv4() }]);

  const onAddChoice = () => {
    setResult([...result, { name: '', value: '', id: uuidv4() }]);
  };

  const onRemoveChoice = (idx) => {
    //删除指定的表单项
    const newResult = result.filter((item, index) => index !== idx);
    setResult(newResult);
    onChange(newResult);
  };

  const onNameChange = (e, idx) => {
    let newResult = [...result];
    newResult.filter(item => item.id === idx)[0].name = e.target.value;
    setResult(newResult);
    onChange(newResult);
  };

  const onValueChange = (e, idx) => {
    let newResult = [...result];
    newResult.filter(item => item.id === idx)[0].value = e.target.value;
    setResult(newResult);
    onChange(newResult);
  };

  return (
    <div>
      {result.map((item, index) => {
        return (
          <div style={{ display: 'flex', alignItems: 'center', marginTop: index === 0 ? 0 : '20px' }}>

            <Input maxLength={30} onInput={(e) => onNameChange(e, item.id)} style={{ width: '200px' }}
                   placeholder={'请输入产品参数名称'} />
            {
              mode === 'multiple' &&
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div>&nbsp; ~ &nbsp;</div>

                <Input maxLength={70} onInput={(e) => onValueChange(e, item.id)} style={{ width: '300px' }}
                       placeholder={'请输入产品参数值'} />
              </div>
            }
            {result.length < maxLen ? (
              <PlusCircleOutlined
                style={{ marginLeft: '20px', fontSize: '22px', color: '#999999' }}
                onClick={onAddChoice} />
            ) : null}

            {result.length > 1 && (
              <MinusCircleOutlined onClick={() => {
                onRemoveChoice(index);
              }} style={{ marginLeft: '20px', fontSize: '22px', color: '#999999' }} />
            )}
          </div>
        );
      })}
    </div>
  );
};